package com.service.impl;

import com.afbx.common.convert.Convert;
import com.entity.Course;
import com.mapper.StudentMapper;
import com.mapper.TeacherMapper;
import com.service.ISettleService;
import com.util.CollectionUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 毕业结算的服务类
 *
 * @Author ri.yang
 * @Since 2016/1/9.
 */
@Service
public class SettleServiceImpl implements ISettleService {
    @Resource
    private StudentMapper studentMapper;
    @Resource
    private TeacherMapper teacherMapper;
    /**
     * 计算该该学生的实际所得学分
     *
     * @param stuNo
     * @return
     */
    public BigDecimal calculateCredit(String stuNo) {
        List<Integer> totalScores = studentMapper.getTotalCredit(stuNo);
        BigDecimal scores = BigDecimal.ZERO;
        //计算该学生对应的总学分
        for (Integer score : totalScores) {
            scores = scores.add(BigDecimal.valueOf(score));
        }
        return scores;
    }

    /**
     * 根据考试成绩是否及格判断 若大于60得分 获取响应学分 否则重置学分为0
     *
     * @param stuNo
     * @return
     */
    public List<Map<String, Object>> resetCredit(String stuNo) {
        //获取该学生的所有课程对应的考分
        List<Map<String, Object>> scores = studentMapper.findByStuNo(stuNo);
        if (CollectionUtil.isNotEmpty(scores)) {
            for (Map<String, Object> map : scores) {
                BigDecimal score = BigDecimal.ZERO;
                //获取该课程的对应的分数
                if (map.containsKey("score")) {
                    score = (BigDecimal) map.get("score");
                }
                //判断是否有不及格的课程
                if (Convert.asInt(score) < Course.PASS_SOCRE) {
                    //若不及格则学分置为0
                    map.put("score", BigDecimal.ZERO);
                    //更新学生的学分
                    studentMapper.updateCredit(stuNo, score);
                }
            }
        }
        return scores;
    }


    /**
     * 根据学生总学分判断是否可以毕业
     *
     * @param stuNo
     * @return
     */
    public Boolean canGraduation(String stuNo) {
        BigDecimal credit = studentMapper.getStuCredit(stuNo);
        if (calculateCredit(stuNo).compareTo(credit) < 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取所有学生专业的毕业实际信息(专业总学分，毕业实际学分，专业。。。）
     *
     * @return
     */
    public List<Map<String, Object>> getGraduationInfo() {
        List<Map<String, Object>> infos = studentMapper.selectAllCredit();
        for (Map<String, Object> map : infos) {
            //获取学生的学号
            String stuNo = Convert.asString(map.get("stuNo"));
            //获取该学生的毕业时实际学分
            BigDecimal actualCredit = calculateCredit(stuNo);
            //添加该学生的实际学分
            if (!map.containsKey("actualCredit")) {
                map.put("actualCredit", actualCredit);
            }
        }
        return infos;
    }
}
